package com.fly.demo.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.fly.demo.web.entity.SysPermission;
import com.fly.demo.web.entity.SysRole;
import com.fly.demo.web.entity.Users;
import com.fly.demo.web.service.UsersService;

import lombok.extern.log4j.Log4j2;

/**
 * 
 * @desc shiro核心配置类
 * @author 00fly
 * 
 *         2019年4月29日
 */
@Log4j2
public class MyShiroRealm extends AuthorizingRealm
{
    @Autowired
    UsersService usersService;
    
    // 权限信息，包括角色以及权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
    {
        log.info("-----权限信息------->");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Users user = (Users)principals.getPrimaryPrincipal();
        for (SysRole role : user.getRoleList())
        {// 获取角色
            authorizationInfo.addRole(role.getRole());
            for (SysPermission permission : role.getPermissions())
            {// 获取权限
                authorizationInfo.addStringPermission(permission.getPermission());
            }
        }
        return authorizationInfo;
    }
    
    /* 主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。 */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
        throws AuthenticationException
    {
        log.info("-----身份验证------->");
        String userName = (String)token.getPrincipal();
        log.info("---------->" + token.getCredentials());
        Users users = usersService.findByUserName(userName);
        log.info("-------->" + users);
        if (users == null)
        {
            return null;
        }
        // 实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(users, // 这里传入的是user对象，比对的是用户名，直接传入用户名也没错，但是在授权部分就需要自己重新从数据库里取权限
            users.getPassword(), ByteSource.Util.bytes(users.getCredentialsSalt()), getName());
        return simpleAuthenticationInfo;
    }
}
